﻿using MyCompany.MyProject.Common.LogHelper;
using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCompany.MyProject.Common.DB;

/// <summary>
/// SqlSugarAop 拦截打印 SQL
/// </summary>
public static class SqlSugarAop
{
    /// <summary>
    /// 执行log
    /// </summary>
    /// <param name="sqlSugarClient"></param>
    /// <param name="user"></param>
    /// <param name="table"></param>
    /// <param name="operate"></param>
    /// <param name="sql"></param>
    /// <param name="p"></param>
    /// <param name="config"></param>
    public static void OnLogExecuting(ISqlSugarClient sqlSugarClient,string user,string table,string operate ,string sql, SugarParameter[] p,ConnectionConfig config)
    {
		try
		{
            var logConsole = string.Format($"------------------ \r\n User:[{user}]  Table:[{table}]  Operate:[{operate}] " +
              $"ConnId:[{config.ConfigId}]【SQL语句】: " +
              $"\r\n {UtilMethods.GetNativeSql(sql, p)}");
            //Console.WriteLine(logConsole);
            // 使用 Serialog 输出日志，并释放线程
            using (LogContextExtension.Create.SqlAopPushProperty(sqlSugarClient))
            {
                Log.Information(logConsole);
            }
        }
		catch (Exception ex)
		{
            Log.Error("Error occured OnLogExcuting:" + ex);
            Console.WriteLine("Error occured OnLogExcuting:" + ex);
        }
    }
}
